package com.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 注解验证器
 * @author Administrator
 *
 */
public class AnnotationValidatorUtils {
	/**
	 * 泛型校验器
	 * @param object
	 * @throws AnnotationValidatorException
	 * @throws Exception 
	 * @throws  
	 */
	public static <T> void validator(T object) throws AnnotationValidatorException, Exception{
		Field[] declaredFields = object.getClass().getDeclaredFields();
		Field field;
		Annotation annotation;
		Method method;
		for (int i = 0; i < declaredFields.length; i++) {
			field = declaredFields[i];
			Annotation[] annotations = field.getDeclaredAnnotations();
			for (int j = 0; j < annotations.length; j++) {
				annotation = annotations[j];
				if(annotation instanceof NotNullAnnotation){
					NotNullAnnotation notNullAnnotation = (NotNullAnnotation) annotation;
					//判断是否需要校验该字段
					if(notNullAnnotation.validator()){
						method = object.getClass().getDeclaredMethod("get" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1));
						Object invokeValue = method.invoke(object);
						//抽取底层具体的按断方法 并返回实际校验结果
						//System.out.println(invokeValue + notNullAnnotation.message());
						if(!checkNotNull(invokeValue)){
							throw new AnnotationValidatorException(invokeValue + notNullAnnotation.message());
						};
					};
				}
			}
		}
	}
	
	private static boolean checkNotNull(Object invokeValue) {
		if(invokeValue == null || "".equals((String)invokeValue)){
			return false;
		}
		return true;
	}
}
